<template>
    <zt-dialog v-model="visible" :title="titleName" @confirm="confirmBtn" :loading="isLoading" :showFooter="true"
        :showFullScreen="false" width="600px" height="400px" :showConfirm="true">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80px" class="demo-ruleForm" status-icon>
            <el-form-item label="词典值" prop="itemValue">
                <el-input v-model="ruleForm.itemValue" placeholder="请输入词典值" />
            </el-form-item>
            <el-form-item label="编码前缀" prop="param1">
                <el-input v-model="ruleForm.param1" placeholder="请输入编码前缀" />
            </el-form-item>
        </el-form>
    </zt-dialog>
</template>

<script setup>
import ztDialog from '@/components/zt-dialog/index.vue'
import { ElMessage } from 'element-plus'
import { apiPostCreateCodeDictionaryItem, apiPutUpdateCodeDictionaryItem } from "@/api/admin/codeDictionary/api.js"
const isLoading = ref(false)
const emit = defineEmits(['success', 'update:modelValue'])
const props = defineProps({
    // 当前类型
    currentType: {
        type: String,
        default: 'add'
    },
    // 控制弹窗显示
    visible: {
        type: Boolean,
        default: false
    },
    // 传递过来的值
    objectValue: {
        type: Object,
        default: () => {
            return {}
        }
    }
})

const ruleFormRef = ref(null)
const ruleForm = reactive({
    itemValue: '',// 词条值
    param1: '',// 编码前缀
})
const updateForm = reactive({
    dictId: '',// 词典id
    itemId: '',//词条id
})

const rules = reactive({
    itemValue: [
        { required: true, message: '请输入词条值', trigger: 'blur' },
    ],
    param1: [
        { required: true, message: '请输入编码前缀', trigger: 'blur' },
    ],
})


// 动态获取标题
const titleName = computed(() => {
    return props.currentType == 'edit' ? '修改词条' : '添加词条'
})

// 子组件定义自己的visible
const visible = computed({
    get: () => props.visible,
    set: (value) => {
        // 清除表单字段值
        Object.keys(ruleForm).forEach(key => {
            ruleForm[key] = '';
        });
        ruleFormRef.value.clearValidate()
        emit('update:modelValue', value)
    },
})

// 监听传递过来的值 赋值
watch(() => props.objectValue, (e) => {
    if (e) {
        // 遍历 key 相等的赋值 
        Object.keys(e).forEach(item => {
            Object.keys(ruleForm).forEach(ele => {
                if (item == ele) {
                    ruleForm[ele] = e[item]
                }
            });
            Object.keys(updateForm).forEach(ele => {
                if (item == ele) {
                    updateForm[ele] = e[item]
                }
            });
        });
    }
}, {
    deep: true,
    immediate: true
})

// 确认按钮
async function confirmBtn() {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
            // 编辑时执行
            if (props.currentType == 'edit') {
                editChange()
                return false
            }
            addChange()//添加
        } else {
            const firstValue = Object.values(fields)[0];
            ElMessage({
                message: firstValue[0].message,
                type: 'warning',
            })
        }
    })
}

// 添加方法
function addChange() {
    isLoading.value = true
    apiPostCreateCodeDictionaryItem({ dictId: updateForm.dictId, ...ruleForm, }).then(res => {
        if (res.success) {
            ElMessage({
                message: '词条添加成功',
                type: 'success',
            })
            emit('success')
            visible.value = false
            return false
        }
        console.log(res)
        ElMessage({
            message: res.message,
            type: 'warning',
        })
    }).finally(() => {
        isLoading.value = false
    })
}

// 编辑方法
function editChange() {
    isLoading.value = true
    apiPutUpdateCodeDictionaryItem({ ...ruleForm, ...updateForm }).then(res => {
        if (res.success) {
            ElMessage({
                message: '词条修改成功',
                type: 'success',
            })
            emit('success')
            visible.value = false
            return false
        }
        ElMessage({
            message: res.message,
            type: 'warning',
        })
    }).finally(() => {
        isLoading.value = false
    })
}




</script>

<style lang='scss' scoped></style>